package com.xiaobaibai.security.master_login.handler;

import com.alibaba.fastjson.JSON;
import com.xiaobaibai.entity.UserAdmin;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.security.units.TokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录成功处理层,用于返回token
 */
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    private TokenService tokenService;

    public MyLoginSuccessHandler(TokenService tokenService){
        this.tokenService=tokenService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        String authority=null;
//        for (GrantedAuthority authenticationAuthority : authentication.getAuthorities()) {
//            authority=authenticationAuthority.getAuthority();
//        }
        UserAdmin userAdmin=new UserAdmin();
//        userAdmin.set(authority);//获取身份
        userAdmin.setUsername(authentication.getName());//获取userId
        String token = tokenService.getToken(userAdmin);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        ResponseFormat<String> loginSuccess =
                ResponseFormat.ok("登录成功", token);
        writer.write(JSON.toJSONString(loginSuccess));
    }

}
